from jili.data.data_run import run_frame
from jili.price import price_rq as price_tool
import pandas as pd
import datetime
import rqdatac
from jili.tool.convert import str2datetime
from pandas.api.types import is_datetime64_any_dtype
class data_run_rq(run_frame):
    def rqdata2list(self,k,config,arg,deal):
        if isinstance(k, pd.DataFrame):
            now = datetime.datetime.now()
            index=deal.get("index",["order_book_id","timekey"])
            for i in k.columns:
                if is_datetime64_any_dtype(k[i]):
                    k[i] = k[i].fillna('9999-01-01')
            fillna=deal.get("fillna",None)
            if isinstance(index,str):
                k[index]=k.index
            elif isinstance(index,list):
                n=0
                for i in index:
                    k[i]=k.index.get_level_values(n)
                    n=n+1
            # k["timekey"] = k.index.get_level_values(1)
            # k["order_book_id"] = k.index.get_level_values(0)
            if "order_book_id" in k.columns:
                k["obj"]= k["order_book_id"].apply(lambda x: price_tool.code2obj(x)[0])
                k["mkcode"] = k["order_book_id"].apply(lambda x: price_tool.code2obj(x)[1])

            # k["obj"],k["mkcode"] = k["order_book_id"].apply(lambda x: price_tool.code2obj(x))
            k["uptime"] = now
            k.index = range(len(k))
            if fillna is not None:
                k.fillna(fillna, inplace=True)
            kk = k.to_dict('records')
            if "timekey" in kk[0].keys():
                if isinstance(kk[0]["timekey"],datetime.date):
                    for i in kk:
                        i["timekey"]=datetime.datetime(i["timekey"].year,i["timekey"].month,i["timekey"].day)
                elif isinstance(kk[0]["timekey"],str):
                    for i in kk:
                        i["timekey"]=str2datetime(i["timekey"])
        else:
            kk = []
        return kk
    def stop_ll(self,use_rate=None,no_use_size_M=None,check_times=None):
        isclose = False
        # if check_times is not None:
            # now = datetime.datetime.now()
        if check_times is None:
            r0 = True
        else:
            r0=self.stop_times(check_times)
        if r0:
            r = rqdatac.user.get_quota()
            if use_rate is not None:
                r0=r["bytes_used"]/r["bytes_limit"]
                if r0>= use_rate:
                    isclose = True
            if no_use_size_M is not None:
                r0 = r["bytes_limit"]-r["bytes_used"]
                r0=r0/1024/1024
                if r0 <= no_use_size_M:
                    isclose = True
        return isclose

    def rqclass2dict(self,i,now):
        r = {}
        for k, v in i.__dict__.items():
            if k[0] != "_":
                r[k] = v
        if "order_book_id" in r.keys():
            if "." in r["order_book_id"]:
                r["obj"], r["mkcode"] = r["order_book_id"].split(".")
            else:
                r["obj"] = r["order_book_id"]
                r["mkcode"] = price_tool.rq2ats_mkcode[r["exchange"]]
                r["order_book_id"] = r["order_book_id"] + "." + r["exchange"]
        r["uptime"] = now
        return r

    def rqclass2list(self,k, config, arg, deal):
        r = []
        now = datetime.datetime.now()
        if isinstance(k, list):
            for i in k:
                r.append(self.rqclass2dict(i,now))
        else:
            r = [self.rqclass2dict(k,now)]
        return r